package com.blog.config;

import com.blog.Interceptor.JwtIntercept;
import com.blog.common.json.JsonObjectMapper;
import com.blog.common.prop.JwtProp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Autowired
   private JwtProp jwtProp;

    @Autowired
    private JwtIntercept jwtIntercept;

    // 将我们自定的转换器添加进行消息转换列表中
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mc = new MappingJackson2HttpMessageConverter();
        mc.setObjectMapper(new JsonObjectMapper());
        converters.add(0, mc);
    }

    // 处理跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许跨域请求的路径
                .allowedOriginPatterns("*") // 允许跨域请求的域名
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许跨域请求的方法
                .allowedHeaders("*") // 允许跨域请求的header
                .allowCredentials(true) // 允许跨域请求的session
                .maxAge(3600); // 配置跨域请求缓存时间
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtIntercept)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login" , "/user/register" , "/article/**","/upload");

    }
}
